<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex; justify-content: space-between; margin-bottom: 20px;">
      <div class="filter-left">
        <el-form :inline="true" :model="listQuery" class="demo-form-inline">
          <el-form-item label="任务名称">
            <el-input
              v-model="listQuery.tm"
              placeholder="请输入任务名称"
              style="width: 200px;"
              size="mini"
              clearable
              @keyup.enter.native="handleFilter"
              @clear="handleFilter"
            />
          </el-form-item>
          <el-form-item label="档号">
            <el-input
              v-model="listQuery.dh"
              placeholder="请输入档号"
              style="width: 150px;"
              size="mini"
              clearable
              @keyup.enter.native="handleFilter"
              @clear="handleFilter"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              size="mini"
              style="width: 120px"
              @change="handleFilter"
            >
              <el-option label="未执行" :value="0" />
              <el-option label="已执行" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
            >
              搜索
            </el-button>
            <el-button
              size="mini"
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="filter-right">
        <el-button size="mini" type="primary" icon="el-icon-back" @click="goBack">
          返回任务列表
        </el-button>
        <el-button size="mini" type="success" icon="el-icon-refresh" @click="refreshList" style="margin-left: 10px;">
          刷新队列
        </el-button>
      </div>
    </div>

    <div class="myTable" style="min-height: 600px;">
      <div style="margin-bottom: 10px;">
        <el-button
          size="mini"
          type="danger"
          icon="el-icon-delete"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <el-table 
        :key="tableKey" 
        :data="list" 
        fit 
        size="mini" 
        highlight-current-row 
        style="width: 100%;"
        v-loading="listLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" prop="id" align="center" min-width="50" />
        <el-table-column label="任务名称" prop="tm" align="center" min-width="150" show-overflow-tooltip />
        <el-table-column label="档案ID" prop="article_id" align="center" min-width="150" show-overflow-tooltip />
        <el-table-column label="档号" prop="dh" align="center" min-width="150" show-overflow-tooltip />
        <el-table-column label="抽取任务ID" prop="obtain_id" align="center" min-width="100" />
        <el-table-column label="创建时间" prop="create_time" align="center" min-width="150" />
        <el-table-column label="更新时间" prop="update_time" align="center" min-width="150" />
        <el-table-column label="状态" prop="status" align="center" min-width="100">
          <template slot-scope="{row}">
            <div v-if="row.status === 1">
              <span class="statusPie success" />
              <span class="text">已执行</span>
            </div>
            <div v-else>
              <span class="statusPie danger" />
              <span class="text">未执行</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" min-width="180" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <!-- <el-button 
              v-if="row.status === 1"
              type="primary" 
              size="mini" 
              @click="handleReprocess(row)"
            >
              重新执行
            </el-button> -->
            <!-- <el-button 
              v-else
              type="success" 
              size="mini" 
              @click="handleProcess(row)"
            >
              执行
            </el-button> -->

            <el-button size="mini" type="primary" @click="handleArchiveDetail(row)">
              查看档案
            </el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="handleDelete(row,$index)"
            >
              删除
            </el-button>
            <el-button 
              size="mini" 
              type="info" 
              @click="handleDetails(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination 
        v-show="total>0"
        size="mini"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @pagination="getList" 
      />
    </div>

    <!-- 队列详情对话框 -->
    <el-dialog title="队列项详情" :visible.sync="detailsVisible" width="80%">
      <el-descriptions :column="1" border style="margin-bottom: 20px;">
        <el-descriptions-item label="ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ detailData.tm }}</el-descriptions-item>
        <el-descriptions-item label="档案ID">{{ detailData.article_id }}</el-descriptions-item>
        <el-descriptions-item label="档号">{{ detailData.dh }}</el-descriptions-item>
        <el-descriptions-item label="抽取任务ID">{{ detailData.obtain_id }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.create_time }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.update_time }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
            {{ detailData.status === 1 ? '已执行' : '未执行' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <div class="mingzhong-data">
        <div class="data-title">抽取结果</div>
        <pre class="json-viewer">{{ mingzhongJson }}</pre>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailsVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { api } from '@/api/template'
import Pagination from '@/components/Pagination'

export default {
  name: 'QueueList',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: false,
      selectedIds: [],
      listQuery: {
        page: 1,
        limit: 10,
        tm: undefined,
        dh: undefined,
        status: undefined,
        obtain_id: undefined
      },
      detailsVisible: false,
      detailData: {},
      mingzhongData: {},
      mingzhongJson: '',
      activeTab: 'basic'
    }
  },
  created() {
    // 如果URL中有taskId参数，自动添加到查询条件中
    if (this.$route.query.taskId) {
      this.listQuery.obtain_id = this.$route.query.taskId
    }
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const response = await api('getQueueList', this.listQuery)
        if (response.code === 200) {
          this.list = response.data.resultList
          this.total = response.totalCount
        }
      } catch (error) {
        console.error('获取列表失败:', error)
      }
      this.listLoading = false
    },
    handleSelectionChange(val) {
      this.selectedIds = val.map(item => item.id)
    },
    async handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的记录')
        return
      }
      
      try {
        await this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await api('batchDeleteQueue', { ids: this.selectedIds })
        if (response.code == 200) {
          this.$notify({
            title: '成功',
            message: response.message || '批量删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify({
            title: '失败',
            message: response.message,
            type: 'error',
            duration: 2000
          })
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },
    async handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const data = { ids: [row.id] }
          const response = await api('batchDeleteQueue', data)
          if (response.code == 200) {
            this.$notify({
              title: '成功',
              message: response.message || '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'error',
              duration: 2000
            })
          }
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleProcess(row) {
      try {
        const response = await api('processObtainQueue', { id: row.id })
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '任务已执行',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      } catch (error) {
        console.error('执行失败:', error)
      }
    },
    handleArchiveDetail(row) {
      window.open(`/dashboard/docview?id=${row.article_id}`, '_blank')
    },
    async handleReprocess(row) {
      try {
        const response = await api('reprocessObtainQueue', { id: row.id })
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '任务已重新执行',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }
      } catch (error) {
        console.error('重新执行失败:', error)
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      // 保留taskId参数
      const obtainId = this.listQuery.obtain_id
      
      this.listQuery = {
        page: 1,
        limit: 10,
        tm: undefined,
        dh: undefined,
        status: undefined,
        obtain_id: obtainId // 保留原有的任务ID筛选
      }
      this.getList()
    },
    refreshList() {
      this.getList()
    },
    goBack() {
      this.$router.push('/template/extractiontaskmanagement')
    },
    async handleDetails(row) {
      this.detailData = Object.assign({}, row)
      
      try {
        this.mingzhongData = {} // 清空上一次的数据
        this.mingzhongJson = '' // 清空上一次的JSON字符串
        this.detailsVisible = true // 先显示弹窗
        
        // 加载民政数据
        const response = await api('getmingzhongdata', { id: row.id })
        
        if (response.code == 200) {
          this.mingzhongData = response.data
          // 将数据格式化为美观的JSON字符串
          this.mingzhongJson = JSON.stringify(response.data, null, 2)
        } else {
          this.$notify({
            title: '提示',
            message: response.message || '获取民政数据失败',
            type: 'warning',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('获取详情数据失败:', error)
        this.$notify({
          title: '错误',
          message: '获取详情数据失败',
          type: 'error',
          duration: 2000
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .filter-container {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  }

  .filter-left {
    flex: 1;
  }

  .filter-right {
    display: flex;
    align-items: center;
  }
  
  .statusPie {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 5px;
    
    &.success {
      background-color: #67C23A;
    }
    
    &.danger {
      background-color: #F56C6C;
    }
  }
  
  .text {
    font-size: 12px;
    vertical-align: middle;
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.json-viewer {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  font-family: 'Monaco', 'Menlo', 'Consolas', 'Courier New', monospace;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 500px;
  overflow-y: auto;
  font-size: 14px;
  line-height: 1.5;
}

.mingzhong-data {
  margin-top: 20px;
}

.data-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding-left: 5px;
  border-left: 3px solid #409EFF;
}
</style>
